<template>
  <div class="app-wrapper" :class="{ 'collapse': isCollapse }">
    <!-- 侧边栏 -->
    <div class="sidebar-container" :class="{ 'collapse': isCollapse }">
      <div class="logo">
        <img src="@/assets/airline-logo.png" alt="Logo">
        <h1>航班管理系统</h1>
      </div>

      <el-menu
        router
        :default-active="$route.path"
        class="sidebar-menu"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
        :collapse="isCollapse"
        unique-opened
        :collapse-transition="false"

      >
        <!-- 首页 -->
        <el-menu-item index="/home/dashboard">
          <el-icon><HomeFilled/></el-icon>
          <span>首页信息</span>
        </el-menu-item>

        <!-- 航班管理 -->
        <el-sub-menu index="flight"  @click="(e) => e.stopPropagation()">
          <template #title>
            <el-icon><Tickets/></el-icon>
            <span>航班管理</span>
          </template>
          <el-menu-item index="/home/flight-info">
            <el-icon><Monitor/></el-icon>
            <span>航班飞机信息</span>
          </el-menu-item>
          <el-menu-item index="/home/flight-time">
            <el-icon><Clock/></el-icon>
            <span>航班时间信息</span>
          </el-menu-item>
          <el-menu-item index="/home/airport-info" v-if="isAdmin">
            <el-icon><List/></el-icon>
            <span>机场信息管理</span>
          </el-menu-item>
        </el-sub-menu>

        <!-- 变更管理 -->
        <el-sub-menu index="change">
          <template #title>
            <el-icon><Location/></el-icon>
            <span>航班变更</span>
          </template>
          <el-menu-item index="/home/route-change">
            <el-icon><Connection/></el-icon>
            <span>航班航线变更</span>
          </el-menu-item>
          <el-menu-item index="/home/route-history">
            <el-icon><Histogram/></el-icon>
            <span>变更历史</span>
          </el-menu-item>
        </el-sub-menu>

        <!-- 地面服务 -->
        <el-sub-menu index="ground">
          <template #title>
            <el-icon><Location/></el-icon>
            <span>地面服务</span>
          </template>
          <el-menu-item index="/home/luggage">
            <el-icon><Suitcase/></el-icon>
            <span>行李转盘管理</span>
          </el-menu-item>
          <el-menu-item index="/home/boarding-gate">
            <el-icon><Flag/></el-icon>
            <span>登机口管理</span>
          </el-menu-item>
        </el-sub-menu>

        <!-- 统计分析 -->
        <el-menu-item index="/home/flight-states" v-if="isAdmin">
          <el-icon><DataAnalysis/></el-icon>
          <span>航班起降统计</span>
        </el-menu-item>

        <!-- 账号管理 -->
        <el-menu-item index="/home/account-manage" v-if="isAdmin">
          <el-icon><User/></el-icon>
          <span>账号管理</span>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 主内容区 -->
    <div class="main-container">
      <!-- 顶部导航栏 -->
      <div class="navbar">
        <div class="left-menu">
          <el-icon @click="toggleCollapse">
            <Expand v-if="isCollapse"/>
            <Fold v-else/>
          </el-icon>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item v-for="item in breadcrumb" :key="item.path">
              {{ item.meta.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div class="right-menu">
          <el-dropdown>
            <div class="avatar-wrapper">
              <el-avatar :size="36" :src="getAvatarUrl(userInfo.avatar)" @error="handleAvatarError">
                {{ userInfo.username?.charAt(0) || 'U' }}
              </el-avatar>
              <span class="username">{{ userInfo.username }}</span>
              <el-icon><ArrowDown/></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleProfile">
                  <el-icon><User/></el-icon>
                  个人中心
                </el-dropdown-item>
                <el-dropdown-item divided @click="handleLogout">
                  <el-icon><SwitchButton/></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 内容区 -->
      <div class="app-main">
        <router-view v-slot="{ Component }">
          <transition name="fade-transform" mode="out-in">
            <keep-alive>
              <component :is="Component" :key="$route.path"/>
            </keep-alive>
          </transition>
        </router-view>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import userApi from '@/api/users'
import {
  HomeFilled, Tickets, Monitor, Clock, List,
  Connection, Histogram, Location, Suitcase,
  DataAnalysis, User, Expand, Fold, ArrowDown,
  SwitchButton, Flag
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const store = useStore()

const userInfo = computed(() => store.state.user || {
  username: '',
  email: '',
  phone: '',
  gender: '',
  avatar: '',
  role: '',
  createTime: '',
  lastLoginTime: ''
})

const isCollapse = ref(false)
const breadcrumb = computed(() => {
  return route.matched.filter(item => item.meta && item.meta.title)
})

const isAdmin = computed(() => {
  return userInfo.value.role?.toLowerCase() === 'admin'
})

const getAvatarUrl = (avatarPath) => {
  if (!avatarPath) return require('@/assets/default-avatar.png')
  try {
    return require(`@/assets${avatarPath.startsWith('/') ? avatarPath : '/' + avatarPath}`)
  } catch (e) {
    console.error('头像加载失败:', e)
    return require('@/assets/default-avatar.png')
  }
}

const handleAvatarError = () => {
  return require('@/assets/default-avatar.png')
}

const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

const handleProfile = () => {
  router.push('/home/profile')
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    store.commit('clearUser')
    localStorage.removeItem('token')
    localStorage.removeItem('role')

    await router.push('/login')
    ElMessage.success('退出成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('退出失败: ' + error.message)
    }
  }
}

onMounted(async () => {
  if (!store.state.user?.id) {
    try {
      const res = await userApi.getCurrentUser()
      store.commit('setUser', res)
    } catch (error) {
      console.error('获取用户信息失败:', error)
      ElMessage.error('获取用户信息失败')
    }
  }
})
</script>

<style lang="scss" scoped>
/* 样式保持不变，与之前相同 */
.app-wrapper {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.sidebar-container {
  width: 210px;
  height: 100%;
  background-color: #304156;
  transition: width 0.28s;
  position: relative;
  z-index: 1001;

  &.collapse {
    width: 64px;

    .logo h1 {
      display: none;
    }
  }

  .logo {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    img {
      width: 30px;
      height: 30px;
      margin-right: 10px;
    }

    h1 {
      color: #fff;
      font-size: 16px;
      margin: 0;
      white-space: nowrap;
      transition: all 0.3s;
    }
  }

  .sidebar-menu {
    border-right: none;
    height: calc(100% - 60px);
  }
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .navbar {
    height: 60px;
    background-color: #fff;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;

    .left-menu {
      display: flex;
      align-items: center;

      .el-icon {
        margin-right: 15px;
        font-size: 20px;
        cursor: pointer;
        color: #666;
      }
    }

    .right-menu {
      .avatar-wrapper {
        display: flex;
        align-items: center;
        cursor: pointer;

        .username {
          margin: 0 8px;
          font-size: 14px;
        }
      }
    }
  }

  .app-main {
    flex: 1;
    padding: 20px;
    overflow: auto;
    background-color: #f5f7fa;
  }
}

.fade-transform-leave-active,
.fade-transform-enter-active {
  transition: all 0.5s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

@media (max-width: 768px) {
  .sidebar-container {
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    z-index: 1001;

    &.collapse {
      width: 0;
    }
  }

  .main-container {
    margin-left: 0;

    .navbar {
      padding: 0 10px;

      .left-menu .el-breadcrumb {
        display: none;
      }

      .right-menu .username {
        display: none;
      }
    }
  }
}
</style>
